
# -*- coding: utf-8 -*-

import debug
import urllib2
import base64
import threading
import logging

from CamBase import CamBase

class DummyDR(CamBase):
	'''
	ダミーカメラ用カメラコントロールクラス
	'''
	@debug.entry
	def __init__(self, config):
		self.model = config['model']
		self.uri = config['address']
		self.username = config['username']
		self.passwd = config['passwd']
		self.MovieCaptureThread = None
		self.MovieEventObj = None

	def __getResObj(self, uri):
		passmgr = urllib2.HTTPPasswordMgrWithDefaultRealm()
		passmgr.add_password(None, uri, self.username, self.passwd)
		authInfo = urllib2.HTTPBasicAuthHandler(passmgr)
		opener = urllib2.build_opener(authInfo)
		urllib2.install_opener(opener)
		reqObj = urllib2.Request(uri)
		
		try:
			resObj = urllib2.urlopen(reqObj)
		except urllib2.HTTPError, e:
			logging.debug(e.msg)
			return {'Success':False, 'Response':None, 'Message':e.msg}
		except urllib2.URLError, e:
			logging.debug(e)
			return {'Success':False, 'Response':None, 'Message':e}
		
		return {'Success':True, 'Response':resObj, 'Message':'OK'}

	def get_content_length(self, data):
		if data[0:15] != 'Content-Length:':
			return None
		return int(data[16:])

	def MovieCaptureLoop(self, target, storage):
		i = 0
		camCaptures = self.__getResObj('http://'+self.uri+'/cgi/mjpg/mjpeg.cgi')
		
		if camCaptures['Success'] is False:
			logging.debug(camCaptures['Message'])
			return {'Success':False, 'Response':None, 'Message':'Bad Response'}
			
		while not(self.MovieEventObj.is_set()):
			try:
				frameData = camCaptures['Response'].readline()
				content = None

				content_length = self.get_content_length(frameData)
				if content_length is None:
					continue
				else:
					content = camCaptures['Response'].read(content_length)
					# skip crlf
					content = content[2:]
					# skip payload header
					content = content[28:]
					
					if content:
						storage.save_frame(target, content, '.jpg')
			except:
				camCaptures = self.__getResObj('http://'+self.uri+'/cgi/mjpg/mjpeg.cgi')

	@debug.entry
	def getCamStatus(self):
		'''
		IPカメラの接続状態を取得する
		return:
			Success:True/False
			Response: OK/None
			Message: OK/Bad Response
		'''
		res = self.__getResObj('http://'+self.uri+'/rdr.cgi')
		if res['Success'] is False:
			logging.debug(res['Message'])
			return {'Success':False, 'Response':None, 'Message':'Bad Response'}
		else:
			return {'Success':True, 'Response':'OK', 'Message':'OK'}

	@debug.entry
	def getVideoFormat(self):
		'''
		現在のビデオフォーマットを取得
		return: 
			Success: True/False
			Responce: 現在のビデオフォーマット(文字列)/None
			Message: OK/Bad Response
		'''
		vformat = "MJPEG"
		return {'Success':True, 'Response':vformat, 'Message':'OK'}

	@debug.entry
	def getResolution(self):
		'''
		IPカメラの現在の解像度を取得する
		return:
			Success: True/False
			Responce: 現在の解像度(文字列)/None
			Message: OK/Bad Response
		'''
		return {'Success':True, 'Response':"640*480", 'Message':'OK'}
	
	@debug.entry
	def getFps(self):
		'''
		現在のフレームレートを取得する
		return: 
			Success: True/False
			Responce: フレームレート(整数値)/None
			Message: OK/Bad Response
		'''
		return {'Success':True, 'Response':30, 'Message':'OK'}

	@debug.entry
	def getSnapshot(self):
		'''
		IPカメラから静止画を取得する
		return:
			Success: True/False
			Responce: 画像データ(バイナリ, JPEG)/None
			Message: OK/Bad Response
		'''
		res = self.__getResObj('http://'+self.uri+'/cgi/jpg/image.cgi')
		if res['Success'] is False:
			logging.debug(res['Message'])
			return {'Success':False, 'Response':None, 'Message':res['Message']}
		else:
			return {'Success':True, 'Response':res['Response'].read(), 'Message':'OK'}

		
	@debug.entry
	def startMovieCapture(self, target, storage):
		'''
		IPカメラで動画キャプチャを開始する
		target: 撮影対象となるカメラのコンフィグ名
			ex.) cam1, cam2, cam3 ...
		storage: 保存するストレージクラス
		return: 
			Success: True/False
			Responce: OK/None
			Message: OK/NG
		'''
		if self.MovieCaptureThread is not None:
			logging.debug('movie capture thread is started already.')
			return {'Success':False, 'Response':None, 'Message':'movie capture thread is started already.'}

		self.MovieEventObj      = threading.Event()
		self.MovieEventObj.clear()

		self.MovieCaptureThread = threading.Thread(target=self.MovieCaptureLoop, args=(target, storage))
		self.MovieCaptureThread.start()

		return {'Success':True, 'Response':'OK', 'Message':'OK'}

	@debug.entry
	def endMovieCapture(self):
		'''
		IPカメラの動画キャプチャを終了させる
		return:
			Success: True/False
			Responce: OK/None
			Message: OK/None
		'''
		if self.MovieCaptureThread is None:
		    return {'Success':False, 'Response':None, 'Message':'movie capture thread is not running.'}
		
		# Wait to Finish Thread
		while self.MovieCaptureThread.is_alive():
			self.MovieEventObj.set()
			self.MovieCaptureThread.join(0.1)

		logging.debug('movie capture thread is finished.')
		self.MovieCaptureThread = None
		self.MovieEventObj      = None
            
		return {'Success':True, 'Response':'OK','Message':'OK'}
